package com.zlx.springclouddemo.superstar.service;

import cn.hutool.core.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.ServerSocket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@Service
public class SuperstarService {
    private Logger logger = LoggerFactory.getLogger(SuperstarService.class);

    String mysqlDriver = "com.mysql.cj.jdbc.Driver";
    String url = "jdbc:mysql://192.168.1.53:3306/mysql";
    String newUrl = "jdbc:mysql://192.168.1.53:3306/";
    String username = "superadmin";
    String password = "superadmin";

    @Value("${config.path}")
    String configPath;

    public String createSchool(String schoolId){
        Connection conn = null;
        Statement smt = null;
        try {
            Class.forName(mysqlDriver);
            String createDbSQL = "create schema zlx_"+schoolId+" default character set utf8mb4 collate utf8mb4_general_ci;";
             conn = DriverManager.getConnection(url, username, password);
             smt = conn.createStatement();
            ResultSet resultSet = smt.executeQuery("SHOW DATABASES LIKE 'zlx_"+schoolId+"';");
            if(resultSet.next()){
             String db = resultSet.getString(1);
                logger.info("已存在数据库："+db);
            }else{
                int i = smt.executeUpdate(createDbSQL);
                logger.info("为新的学校创建数据库，结果为："+i);
            }
            smt.close();
            conn.close();
            ServerSocket s = new ServerSocket(0);
            StringBuffer applicationYML = new StringBuffer();
            applicationYML.append("server.port=");
            applicationYML.append(s.getLocalPort());
            applicationYML.append("\nspring.application.name=");
            applicationYML.append(schoolId);

            applicationYML.append("\nspring.datasource.url=");
            applicationYML.append("jdbc:mysql://192.168.1.53:3306/zlx_");
            applicationYML.append(schoolId);
            applicationYML.append("?useSSL=false");

            applicationYML.append("\nspring.datasource.username=superadmin");
            applicationYML.append("\nspring.datasource.password=superadmin");
            applicationYML.append("\nspring.datasource.driverClassName=com.mysql.cj.jdbc.Driver");
            applicationYML.append("\nspring.datasource.max-active=20");
            applicationYML.append("\nspring.datasource.max-idle=8");
            applicationYML.append("\nspring.datasource.min-idle=8");
            applicationYML.append("\nspring.datasource.initial-size=10");

            applicationYML.append("\nspring.jpa.database=MYSQL");
            applicationYML.append("\nspring.jpa.show-sql=true");
            applicationYML.append("\nspring.jpa.hibernate.ddl-auto=update");
            applicationYML.append("\nspring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy");
            applicationYML.append("\nspring.jpa.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect");

            applicationYML.append("\neureka.client.healthcheck.enabled=true");
            applicationYML.append("\neureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka");
            applicationYML.append("\neureka.instance.prefer-ip-address=true");

            applicationYML.append("\nschool.id=");
            applicationYML.append(schoolId);
            applicationYML.append("\ninfo.schoolId=");
            applicationYML.append(schoolId);

            FileUtil.appendString(applicationYML.toString(),configPath+"/application-"+schoolId+".properties","utf8");
            String[] ss = {schoolId};
            Runtime.getRuntime().exec(configPath+"/runjar.bat",ss);
            return "学校创建成功！";
        } catch (Exception e) {
            logger.error("创建学校失败",e);
        }
        return "创建学校失败！";
    }
}
